import Axios from 'axios'
import Router from '../router'
import {Toast, Indicator} from 'mint-ui'

/**
 * 设置公共请求头access_token
*/
// const access_token = utils.getCookie('access_token');
// Axios.defaults.headers.common['Authorization'] = `bearer ${access_token}`;

/**
 * get
 */
export const $get = (url, params) => {
  loading()
  return new Promise((resolve, reject) => {
    Axios.get(url, {
      params: {
        ...params,
        _t: new Date().getTime()
      }
    }).then((res) => {
      if (res.status === 200) {
        if (res.data.status === 'y') {
          resolve(res.data.result || res.data.info)
        } else {
          failMessage(res.data.info)
        }
      } else {
        failMessage('获取数据失败')
        reject(res)
      }
    }).catch((mes) => {
      failMessage('获取数据失败')
      reject(mes)
    })
  })
}
/**
 * post
 */
export const $post = (url, params, back = false) => {
  loading()
  return new Promise((resolve, reject) => {
    Axios.post(url, params).then((res) => {
      Indicator.close()
      if (res.status === 200) {
        if (res.data.status === 'y') {
          resolve(res.data.result || res.data.info)
        } else {
          failMessage(res.data.info, back)
          return false
        }
      } else {
        failMessage('获取数据失败')
        reject(res)
      }
    }).catch((err) => {
      Indicator.close()
      failMessage('网络连接失败')
      reject(err)
    })
  })
}

/**
 * 弹框消息
 * @param {string} msg
 */
function failMessage (msg, goBack) {
  Toast({
    message: msg,
    position: 'bottom',
    duration: 3000
  })
  if (goBack) {
    setTimeout(() => {
      Router.go(-1)
    }, 2000)
  }
}
/**
 * loading界面
 */
function loading () {
  Indicator.open({
    text: 'loading...',
    spinnerType: 'snake'
  })
}
